/**
 * @name ColorPicker
 * @author darcrand
 * @desc 颜色选择器
 */

import React, { Component } from 'react'
import { Popover } from 'antd'
import styles from './styles.module.less'

const COLORS = [
  '#1cc7d0',
  '#2dde98',
  '#ffc168',
  '#ff6c5f',
  '#ff4f81',
  '#b84592',
  '#8e43e7',
  '#3369e7',
  '#00aeff',
  '#e4002b',
  '#49a942',
  '#fe5000',
  '#74d2e7',
  '#a0ac48',
  '#2e9df7',
  '#b9dca4',
  '#ffc2e5',
  '#ffaaaa',
  '#dbc5b0',
  '#32d473',
  '#6633cc',
  '#ff2052',
  '#aeb6b8',
  '#f10087',
  '#41afa5',
  '#50667f',
  '#f3ec19',
  '#557665',
  '#b6acd1',
  '#0000e6',
  '#17ad49',
  '#c8aa76',
]

const Fills = () =>
  Array(20)
    .fill(0)
    .map(v => <li key={Math.random()} className={styles.fill} />)

class ColorPicker extends Component {
  static defaultProps = {
    value: undefined,
    defaultValue: undefined,
    onChange: value => {},

    className: '',
    style: {},
  }

  state = {
    value: undefined,
    lastValue: undefined,

    visible: false,
  }

  static getDerivedStateFromProps(props, state) {
    if (props.value !== state.lastValue) {
      return { value: props.value, lastValue: props.value }
    }
    return null
  }

  onColorClick = (color = '') => {
    this.setState({ visible: false })
    this.props.onChange && this.props.onChange(color)
  }

  render() {
    const { className, style } = this.props
    const { visible, value } = this.state

    return (
      <Popover
        visible={visible}
        placement='bottomLeft'
        trigger='click'
        onVisibleChange={vis => this.setState({ visible: vis })}
        content={
          <ul className={styles.container}>
            {COLORS.map(v => (
              <li key={v} className={styles.item} style={{ background: v }} onClick={() => this.onColorClick(v)}></li>
            ))}

            <Fills />
          </ul>
        }
      >
        <button
          className={[styles.btn, className].filter(Boolean).join(' ')}
          style={{ ...style, background: value || '#ccc' }}
        ></button>
      </Popover>
    )
  }
}

ColorPicker.COLORS = COLORS

export default ColorPicker
